// 封装分类数据业务相关代码
import { onMounted, ref } from 'vue';
// 获取路由参数
import { onBeforeRouteUpdate, useRoute } from 'vue-router';
import { getTopCategoryAPI } from '@/apis/category';

export const useCategory = () => {
  const topCategory = ref({});
  const route = useRoute();
  const getTopCategory = async (id = route.params.id) => {
    await getTopCategoryAPI(id).then((data) => {
      let { code, result } = data;
      if (code === '1') {
        topCategory.value = result;
      }
    });
  };
  onMounted(() => getTopCategory());
  // 期望路由参数变化时，重新获取分类数据
  onBeforeRouteUpdate((to) => {
    getTopCategory(to.params.id);
  });

  return {
    topCategory,
  };
};
